package conf

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/cihub/seelog"
	"myFtp/influxdb"
	"sync"
)

var (
	ftpConfOnce             sync.Once
	ftp                     Ftp
	influxdbConnectConfOnce sync.Once
	influxdbConnect         *influxdb.Connect
	sendUrlConfOnce         sync.Once
	sendUrl                 string
	cronConfOnce            sync.Once
	cron                    MyCron
)

func init() {
	err := beego.LoadAppConfig("ini", "conf.conf")
	if err != nil {
		//log.Println(err)
		panic(err)
	}

}

type MyCron struct {
	ExectNotSuccessCron string
	DeleteFileCron      string
	FileMaxCount        int
	SubTime             int
}

type Ftp struct {
	Dir          string
	User         string
	Pass         string
	SPort        string `json:"port"`
	Port         int
	Host         string
	PassivePorts string
}

func InfluxdbConnect() *influxdb.Connect {
	influxdbConnectConfOnce.Do(func() {
		//创建链接Influxdb
		iaddr := beego.AppConfig.String("influxdb::addr")
		ipassword := beego.AppConfig.String("influxdb::password")
		iusername := beego.AppConfig.String("influxdb::username")
		idbname := beego.AppConfig.String("influxdb::dbname")
		itimezone := beego.AppConfig.String("influxdb::timezone")

		influxdbConnect = influxdb.NewConnect(iaddr, iusername, ipassword, idbname, itimezone)
	})
	return influxdbConnect
}

func GetCron() MyCron {
	cronConfOnce.Do(func() {
		cron.ExectNotSuccessCron = beego.AppConfig.String("cron::cron")
		cron.DeleteFileCron = beego.AppConfig.String("cron::deletefilecron")
		cron.FileMaxCount = beego.AppConfig.DefaultInt("cron::fileMaxCount", 2000)
		cron.SubTime = beego.AppConfig.DefaultInt("cron::subTime", 10)
	})
	return cron
}
func GetSenUrl() string {
	sendUrlConfOnce.Do(func() {
		sendUrl = beego.AppConfig.String("sendurl")
	})
	return sendUrl
}

func FtpConf() *Ftp {
	ftpConfOnce.Do(func() {
		ftpConf, err := beego.AppConfig.DIY("ftp")
		port := beego.AppConfig.DefaultInt("ftp::port", 21)
		//port, err := strconv.Atoi(ftpConf["port"])
		if err != nil {
			seelog.Error(err.Error())
		}

		ftpConfByte, err := json.Marshal(ftpConf)
		if err != nil {
			panic(err.Error())
		}
		//ftp.Port = port
		//log.Printf("%v", string(ftpConfByte))
		ftp.Port = port
		json.Unmarshal(ftpConfByte, &ftp)
	})

	return &ftp
}
